package com.jt.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RefreshScope
@RestController
public class ProviderCacheController {
    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @RequestMapping("/provider/cache01")
    public String doUseLocalCache01(){
        return "useLocalCache is " + useLocalCache;
    }

    @RequestMapping("/provider/cache02")
    public List<String> doUseLocalCache02(){
        List<String> cache = new CopyOnWriteArrayList<>();
        if (!useLocalCache){
            return Arrays.asList("A","B");
        }
        if (cache.isEmpty()){
            synchronized (this){
                if (cache.isEmpty()){
                    List<String> list = Arrays.asList("A", "B", "C");
                    cache.addAll(list);
                }
            }
        }
        return cache;
    }


}
